﻿using System.Linq;
using log4net;
using Mate.Caching;
using Mate.Core;
using Mate.Core.Base;
using Mate.Db.Model.System;
using Mate.Dto.System;
using Mate.Framework.BaseController.Admin;
using Mate.System.Service;
using Microsoft.AspNetCore.Mvc;

namespace Mate.Admin.Controllers.System
{
    public class RolesController : BaseController
    {
        private readonly IRolesService rolesService;
        private readonly IMenuService menuService;
        private readonly ILog log;
        private readonly ICacheManager _cache;
        public RolesController( IRolesService rolesService, IMenuService menuService, ICacheManager cache, ILog log)
        {
            this.log = log;
            this.rolesService = rolesService;
            this.menuService = menuService;
            this._cache = cache;
        }

        public IActionResult Index()
        {
            return View();
        }

        #region 获取列表
        [HttpPost]
        public IActionResult GetList(int pageIndex, int pageSize, string Key)
        {
            int recordCount = 0;
            var list = rolesService.GetList(pageIndex, pageSize, Key, ref recordCount);
            var result = new
            {
                rows = list,
                total = recordCount
            };
            return Json(result);
        }
        #endregion

        #region 删除
        [HttpPost]
        public JsonResult Remove(int id)
        {
            var result = new BaseResult();

            var model = rolesService.Get(x => x.id == id);
            if (model == null)
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "参数错误";
                return Json(result);
            }

            if (model.role_name == "超级管理员")
            //if (model.IsSuperAdmin == true || model.RoleId == Consts.SuperAdminRoleId)
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "超级管理员不能删除!";
                return Json(result);
            }

            var b = rolesService.Delete(x => x.id == id);
            if (b > 0)
            {
                _cache.Remove(string.Format(MateCacheKey.CacheRoleKey, id));
                result.ResultCode = ResultCode.Success;
                result.Message = "删除成功";
            }
            else
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "删除失败";
            }
            return Json(result);
        }
        #endregion

        #region 添加
        public ActionResult Create()
        {
            var model = new roles() { order_by = 99 };
            return View(model);
        }

        [HttpPost]
        public JsonResult Create(roles model)
        {
            var result = new BaseResult();

            if (model.role_name == "超级管理员")
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "不能添加超级管理员角色";
                return Json(result);
            }
            
            var obj = rolesService.Insert(model);
            if (obj > 0)
            {
                _cache.Remove(string.Format(MateCacheKey.CacheRoleKey, model.id));
                result.ResultCode = ResultCode.Success;
                result.Message = "添加成功";
            }
            else
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "添加失败";
            }
            return Json(result);
        }
        #endregion

        #region 修改
        public ActionResult Edit(int id)
        {
            var model = rolesService.Get(x => x.id == id);
            if (model == null)
            {
                return Content("参数错误");
            }
            ViewBag.Roles = rolesService.GetRoleAll();
            return View(model);
        }

        [HttpPost]
        public JsonResult Edit(roles model)
        {
            var result = new BaseResult();
            if (model == null)
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "参数错误";
                return Json(result);
            }

            if (model.role_name == "超级管理员")
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "不能修改超级管理员角色";
                return Json(result);
            }

            var b = rolesService.Update(model,
                x => new { x.role_name, x.order_by },
                x => new object[] { x.id });
            if (b > 0)
            {
                _cache.Remove(string.Format(MateCacheKey.CacheRoleKey, model.id));
                result.ResultCode = ResultCode.Success;
                result.Message = "修改成功";
            }
            else
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "修改失败";
            }
            return Json(result);

        }
        #endregion


        #region 权限管理
        /// <summary>
        /// 权限管理
        /// </summary>
        /// <returns></returns>
        public ActionResult AuthorizationManager(int roleid)
        {
            var model = rolesService.Get(x => x.id == roleid);
            if (model == null)
            {
                return Content("参数错误");
            }
            ViewBag.RoleId = roleid;
            ViewBag.RoleName = model.role_name;

            var menuList = menuService.GetList(x => x.id > 0, x => x.order_by);
            var roleMenuList = rolesService.GetRoleMenuList(roleid);
            var result = menuList.Where(x => x.parent_id == 0)
                .Select(x => new MenuModel()
                {
                    id = x.id,
                    menu_type = x.menu_type,
                    menu_name = x.menu_name,
                    IsCurrentPermission = roleMenuList.Any(m => m.menu_id == x.id),
                    children = menuList.Where(m => m.parent_id == x.id)
                    .Select(y => new MenuModel()
                    {
                        id = y.id,
                        menu_type = y.menu_type,
                        menu_name = y.menu_name,
                        IsCurrentPermission = roleMenuList.Any(n => n.menu_id == y.id),
                        children = menuList.Where(z => z.parent_id == y.id)
                        .Select(z => new MenuModel()
                        {
                            id = z.id,
                            menu_type = z.menu_type,
                            menu_name = z.menu_name,
                            IsCurrentPermission = roleMenuList.Any(t => t.menu_id == z.id)
                        }).ToList()
                    }).ToList()
                }).ToList();
            return View(result);
        }

        [HttpPost]
        public JsonResult AuthorizationManager(int roleid, string menuids)
        {
            var result = rolesService.AuthorizationManager(roleid, menuids);
            if (result.ResultCode == ResultCode.Success)
            {
                _cache.RemoveByPattern(string.Format(MateCacheKey.CacheRoleIdMenuCache, roleid.ToString()));
            }
            
            return Json(result);
        }

        #endregion

    }
}